import { SecurityZoneModalComponent } from './../security-zone-modal/security-zone-modal.component';
import { AreaDTO } from './../../../shared/service-proxy/service-proxies';
import { Component, OnInit, ViewChild, ElementRef, Injector } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { loadModules } from 'esri-loader';
import esri = __esri;
import { ServiceProxy, SiteDTO, WarehouseDTO } from '@shared/service-proxy/service-proxies';
import { Locator } from 'protractor';
import { resource } from 'selenium-webdriver/http';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { finalize } from 'rxjs/operators';
import { CreateAreaModalComponent } from './create-area-modal/create-area-modal.component';
import { Router } from '@angular/router';
import { AppConsts } from "@shared/AppConsts";

@Component({
  selector: 'app-area-view',
  templateUrl: './area-view.component.html',
  styleUrls: ['./area-view.component.less']
})
export class AreaViewComponent extends AppComponentBase implements OnInit {

  @ViewChild('mapViewNode') private mapViewEl: ElementRef;
  @ViewChild('createAreaModal') createAreaModal: CreateAreaModalComponent
  @ViewChild('securityZoneModal') securityZoneModal: SecurityZoneModalComponent

  // sites: SiteDTO[] = [];
  companyList: WarehouseDTO[] = [];
  areaList: AreaDTO[] = [];
  // siteId: string;
  areaId: string;
  companyId: string;
  tableHelper: NzTableHelper;

  constructor(injector: Injector,
    private router: Router,

    private _service: ServiceProxy) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }

  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }


  getAreaAll(){
    this._service.getAllAreaDTOUsingGET().subscribe(result => {
      this.areaList = result.result.fieldList;
    })
  }

  getList() {
    this._service.getPageAreasUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, undefined, this.companyId, this.areaId).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;
    });
  }

  // getSites(): void {
  //   this._service.getAllSitesBySiteUsingGET().subscribe(result => {
  //     this.sites = result.result.fieldList;
  //   })
  // }

  getCompanyList() {
    this._service.getAllBySiteIdWarehouseDTOsUsingGET().subscribe(result => {
      this.companyList = result.result.fieldList;
    });
  }

  selectCompany() {
    this.getList();
    this.areaId = undefined;
    this.initializeMap();
  }

  selectArea() {
    // this.initializeMap();
  }

  reset() {
    // this.siteId = undefined;
    this.companyId = undefined;
    this.areaId = undefined;
  }

  showAddress(data: AreaDTO) {
    this.securityZoneModal.show(data.longitude, data.latitude, data.radius);
  }

  async initializeMap() {
    try {
      const [Map, MapView, ScaleBar, TileLayer, Graphic, Circle] = await loadModules([
        'esri/Map',
        'esri/views/MapView',
        'esri/widgets/ScaleBar',
        'esri/layers/TileLayer',
        'esri/Graphic',
        'esri/geometry/Circle',
        'dojo/domReady!'
      ], {
          url: AppConsts.arcgisMapUrl, css: AppConsts.arcgisStyleUrl
        });

      // Set type of map
      const mapProperties: esri.MapProperties = {
        // basemap: this._basemap,
        layers: new TileLayer({
          url: AppConsts.arcgisMapServerUrl
        })
      };

      const map: esri.Map = new Map(mapProperties);
      if (this.tableHelper.items.length) {
        const defaultArea = this.tableHelper.items[0];
        this._center = [defaultArea.longitude, defaultArea.latitude];
      }
      if (this.areaId) {
        const selectAreas = this.tableHelper.items.filter(m => m.id == this.areaId);
        if (selectAreas.length) {
          this._center = [selectAreas[0].longitude, selectAreas[0].latitude];
        }
      }


      // Set type of map view
      const mapViewProperties: esri.MapViewProperties = {
        container: this.mapViewEl.nativeElement,
        center: this._center,
        zoom: this._zoom,
        map: map
      };

      const mapView: esri.MapView = new MapView(mapViewProperties);
      const parentThis = this.tableHelper.items;
      // All resources in the MapView and the map have loaded.
      // Now execute additional processes
      mapView.when(() => {
        const scaleBar = new ScaleBar({
          view: mapView,
          unit: "dual" // The scale bar displays both metric and non-metric units.
        });
        mapView.ui.add(scaleBar, "bottom-left");

        function createArea() {
          // const jsonStr: string = '{"geometry":{"spatialReference":{"wkid":4326},"rings":[[[15.564983111749909,-12.848],[15.564933901323824,-12.84893899086658],[15.564786809205298,-12.84986769395273],[15.56454344696636,-12.850775934193091],[15.564206480934626,-12.851653760717534],[15.563779602980455,-12.852491555874956],[15.563267490068046,-12.853280140606293],[15.56267575301363,-12.854010875012207],[15.562010875012206,-12.854675753013632],[15.561280140606291,-12.855267490068048],[15.560491555874954,-12.855779602980457],[15.559653760717532,-12.856206480934627],[15.55877593419309,-12.856543446966361],[15.557867693952728,-12.8567868092053],[15.556938990866579,-12.856933901323826],[15.556,-12.85698311174991],[15.55506100913342,-12.856933901323826],[15.55413230604727,-12.8567868092053],[15.553224065806909,-12.856543446966361],[15.552346239282466,-12.856206480934627],[15.551508444125044,-12.855779602980457],[15.550719859393707,-12.855267490068048],[15.549989124987793,-12.854675753013632],[15.549324246986368,-12.854010875012207],[15.548732509931952,-12.853280140606293],[15.548220397019543,-12.852491555874956],[15.547793519065372,-12.851653760717534],[15.547456553033639,-12.850775934193091],[15.5472131907947,-12.84986769395273],[15.547066098676174,-12.84893899086658],[15.54701688825009,-12.848],[15.547066098676174,-12.847061009133421],[15.5472131907947,-12.846132306047272],[15.547456553033639,-12.845224065806908],[15.547793519065372,-12.844346239282467],[15.548220397019543,-12.843508444125046],[15.548732509931952,-12.842719859393709],[15.549324246986368,-12.841989124987794],[15.549989124987793,-12.84132424698637],[15.550719859393707,-12.840732509931954],[15.551508444125044,-12.840220397019545],[15.552346239282466,-12.839793519065374],[15.553224065806909,-12.83945655303364],[15.55413230604727,-12.839213190794702],[15.55506100913342,-12.839066098676176],[15.556,-12.839016888250091],[15.556938990866579,-12.839066098676176],[15.557867693952728,-12.839213190794702],[15.55877593419309,-12.83945655303364],[15.559653760717532,-12.839793519065374],[15.560491555874954,-12.840220397019545],[15.561280140606291,-12.840732509931954],[15.562010875012206,-12.84132424698637],[15.56267575301363,-12.841989124987794],[15.563267490068046,-12.842719859393709],[15.563779602980455,-12.843508444125046],[15.564206480934626,-12.844346239282467],[15.56454344696636,-12.845224065806908],[15.564786809205298,-12.846132306047272],[15.564933901323824,-12.847061009133421],[15.564983111749909,-12.848],[15.564983111749909,-12.848]]]},"symbol":{"type":"esriSFS","color":[138,43,226,204],"outline":{"type":"esriSLS","color":[255,255,255,255],"width":0.5,"style":"esriSLSSolid"},"style":"esriSFSSolid"},"attributes":{},"popupTemplate":null}'
          // const transJson = Graphic.fromJSON(JSON.parse(jsonStr));
          // mapView.graphics.add(transJson);
          //
          parentThis.forEach(m => {
            const circle = new Circle({
              center: [m.longitude, m.latitude],
              radius: m.radius
            });
            const graphic = new Graphic({
              geometry: circle,
              symbol: {
                type: "simple-fill",
                outline: {
                  color: [255, 0, 0],
                  width: 2
                }
              }
            });
            mapView.graphics.add(graphic);
          })

        }

        if (parentThis.length) {
          createArea();
        }
      });
    } catch (error) {
      console.log('We have an error: ' + error);
    }

  }

  ngOnInit() {
    if (!this.isGranted('A8_B22_C33_')) {
      if (this.isGranted('A8_B22_C32_')) {
        this.router.navigate(['/center/area/areaCreate']);
      }
    }
    this.getCompanyList();
    this.getAreaAll();
    this.initializeMap();
    this.load();
  }

  showModal(id) {
    this.createAreaModal.show(id);
  }
}
